package task

type Runner struct {
	Controller controllerChan
	Err        controllerChan
	Data       dataChan
	DataSize   int
	longLive   bool
	Dispatcher fn
	Executor   fn
}

//构造函数
func NewRunner(size int, longLive bool, d fn, e fn) *Runner {
	return &Runner{
		Controller: make(chan string, 1),
		Err:        make(chan string, 1),
		Data:       make(chan interface{}, size),
		DataSize:   size,
		longLive:   longLive,
		Dispatcher: d,
		Executor:   e,
	}
}
func (r *Runner) startDispatch() {

	defer func() {
		if !r.longLive {
			close(r.Controller)
			close(r.Err)
			close(r.Data)
		}
	}()
	for {
		select {
		case c := <-r.Controller:
			if c == ReadyToDispatch {
				err := r.Dispatcher(r.Data)
				if err != nil {
					r.Err <- CLOSE
				} else {
					r.Controller <- ReadyToExecute
				}
			} else if c == ReadyToExecute {
				err := r.Executor(r.Data)
				if err != nil {
					r.Err <- CLOSE
				} else {
					r.Controller <- ReadyToDispatch
				}
			}
		case e := <-r.Err:
			if e == CLOSE {
				return
			}
		default:
			//置空即可
		}
	}
}

func (r *Runner) StartAll() {
	r.Controller <- ReadyToDispatch
	r.startDispatch()
}
